#include "exc_screen.h"
#include <QQuickWidget>
#include <QQmlContext>
#include <QLocalSocket>
#include <QMessageBox>
#include <QFileDialog>
#include <QDateTime>
#include <QDate>
#include <QTime>
#include <QDebug>
#include <QtConcurrent>
#include <QFuture>

#include <iostream>
ExcRecordDisplayer::ExcRecordDisplayer()
{
    m_quickMainScreen = new QQuickWidget();
    QUrl source1("qrc:/MainScreen.qml");
    m_quickMainScreen->setResizeMode(QQuickWidget::SizeRootObjectToView);
    m_quickMainScreen->setSource(source1);
    m_quickMainScreen->show();
    m_quickMainScreen->setWindowTitle("EXC Record Displayer V1.1");
    m_quickMainScreen->rootContext()->setContextProperty("excRecordDisplayer", this);

    m_quickWidgetSetting = new QQuickWidget();
    QUrl source("qrc:/Page_7LoadSettingUI.qml");
    m_quickWidgetSetting->setResizeMode(QQuickWidget::SizeRootObjectToView);
    m_quickWidgetSetting->setWindowTitle("time select");
    m_quickWidgetSetting->setSource(source);
    m_quickWidgetSetting->rootContext()->setContextProperty("excRecordDisplayer", this);
}

void ExcRecordDisplayer::sl_selectDatabase()
{
    if(m_fdb.isOpen()) m_fdb.close();
    QString testFileName = QFileDialog::getOpenFileName(m_quickMainScreen,tr(""),"",tr("database(EXC_FACTOR_RECORDER*.db DATA_RECORD.db)")); //选择路径
    if(testFileName.size()==0) return;

    m_fdb = QSqlDatabase::addDatabase("QSQLITE",QString("excdrecorder_read"));
    m_fdb.setDatabaseName(testFileName);

    //1-open
    if(!m_fdb.open()){
        QMessageBox::information(m_quickMainScreen, tr("source requiru fail!"),tr("SQL open fail"));
        return;
    }

    //2-reset field
    QDate t_date;
    QTime t_time;
    QSqlQuery query(m_fdb);
    QObject *t_quickObjectSettingUI = ((QObject *)m_quickWidgetSetting->rootObject());

    //2.1-start time
    if(query.exec("SELECT date,time FROM drecorder where rowid = (select min(rowid) from drecorder)")){
        query.next();
        t_date = query.value(0).toDate();
        t_time = query.value(1).toTime();
    }
    else {
        QMessageBox::information(m_quickMainScreen, tr("query fail"),tr("query min time fail"));
    }
    QMetaObject::invokeMethod(t_quickObjectSettingUI,
                              "setStartTime",
                              Q_ARG(QVariant, QVariant::fromValue(QDateTime(t_date, t_time))));

    //2.2-end time
    if(query.exec("SELECT date,time FROM drecorder where rowid = (select max(rowid) from drecorder)")){
        query.next();
        t_date = query.value(0).toDate();
        t_time = query.value(1).toTime();
    }
    else {
        QMessageBox::information(m_quickMainScreen, tr("query fail"),tr("query max time fail"));
    }
    QMetaObject::invokeMethod(t_quickObjectSettingUI,
                              "setEndTime",
                              Q_ARG(QVariant, QVariant::fromValue(QDateTime(t_date, t_time))));
}


void ExcRecordDisplayer::sl_showLoadSettingUI(int recallWhich)
{

    if(m_quickWidgetSetting->isVisible())
        m_quickWidgetSetting->hide();
    else{
        QVariant t_vari;
        QObject *t_quickObjectSettingUI  = ((QObject *)m_quickWidgetSetting->rootObject());
        t_quickObjectSettingUI->setProperty("recallWhich",recallWhich);
        m_quickWidgetSetting->show();
    }
}

void ExcRecordDisplayer::sl_fullScreen()
{
    if(m_quickMainScreen->isFullScreen())
        m_quickMainScreen->showNormal();
    else
        m_quickMainScreen->showFullScreen();
}

void ExcRecordDisplayer::sl_settingFinishChart()
{
    QDateTime t_time;
    QVector<int> t_vector;
    static QSqlQuery query(m_fdb);

    QFuture < void > future =  QtConcurrent::run([this](){
        QSqlQuery query(m_fdb);
        QVector<int> t_vector;
        qDebug()  << QThread::currentThreadId() << QThread::currentThread();
        QObject *t_quickObjectReadChart  = ((QObject *)m_quickMainScreen->rootObject())->findChild<QObject *>("page_7AnalogReaderChart");
        QMetaObject::invokeMethod(t_quickObjectReadChart , "setBusyIndicator",
                                  Q_ARG(QVariant, QVariant::fromValue(true)));

        for(int i=0;i<2;i++)
        if(query.exec(QString("SELECT date,time,channel,ug,ig,il,usyn,ugd,igd,uk,p,q,f,us FROM drecorder WHERE channel='%1'")
                      .arg(i==0?"A":"B")))
        {
            QVariant t_vari;
            QObject *t_quickObjectSettingUI  = ((QObject *)m_quickWidgetSetting->rootObject());

            t_vari = t_quickObjectSettingUI->property("dateStart");
            QDateTime t_timeStart = t_vari.toDateTime();

            t_vari = t_quickObjectSettingUI->property("dateEnd");
            QDateTime t_timeEnd = t_vari.toDateTime();

            uint t_timeLong = t_timeEnd.toTime_t()-t_timeStart.toTime_t();
            uint t_recorderLastTime=0;
            while(query.next()){
                QDateTime t_dataTime = QDateTime(query.value(0).toDate(), query.value(1).toTime());
                if(t_dataTime>t_timeEnd) break;
                else if(t_dataTime<t_timeStart) continue;

                t_vector.clear();
                t_vector.push_back(query.value(3).toInt());
                t_vector.push_back(query.value(4).toInt());
                t_vector.push_back(query.value(5).toInt());
                t_vector.push_back(query.value(6).toInt());
                t_vector.push_back(query.value(7).toInt());
                t_vector.push_back(query.value(8).toInt());
                t_vector.push_back(query.value(9).toInt());
                t_vector.push_back(query.value(10).toInt());
                t_vector.push_back(query.value(11).toInt());
                t_vector.push_back(query.value(12).toInt());
                t_vector.push_back(query.value(13).toInt());


                QString t_str;
                if(query.value(2).toString().contains('A')) t_str = "addLinePointA";
                else if(query.value(2).toString().contains('B')) t_str = "addLinePointB";

                uint t_recorderNowTime = t_dataTime.toTime_t();
                if(t_recorderNowTime - t_recorderLastTime > 5)
                {
                    if(query.value(2).toString().contains('A'))
                        QMetaObject::invokeMethod(t_quickObjectReadChart , "addScatterPointEndA");
                    else if(query.value(2).toString().contains('B'))
                        QMetaObject::invokeMethod(t_quickObjectReadChart , "addScatterPointEndB");
                }

                QMetaObject::invokeMethod(t_quickObjectReadChart , t_str.toLatin1().data(),
                                          Q_ARG(QVariant, QVariant::fromValue(t_dataTime)),
                                          Q_ARG(QVariant, QVariant::fromValue(t_vector)));

                if(t_recorderNowTime - t_recorderLastTime > 5)
                {

                    if(query.value(2).toString().contains('A'))
                        QMetaObject::invokeMethod(t_quickObjectReadChart , "addScatterPointStartA");
                    else if(query.value(2).toString().contains('B'))
                        QMetaObject::invokeMethod(t_quickObjectReadChart , "addScatterPointStartB");
                }
                t_recorderLastTime = t_recorderNowTime;

                if(query.at()%100==0)
                {
                    long long t_nowTime = (long long)t_timeEnd.toTime_t()-t_recorderNowTime;
                    QMetaObject::invokeMethod(t_quickObjectReadChart , "setBusyIndicatorValue",
                                              Q_ARG(QVariant, QVariant::fromValue((1-(float)t_nowTime/t_timeLong)*100)));
                    qDebug() << query.at();
                    QThread::msleep(300);
                    if(query.at()>2000) break;
                }
            }
        }
        QMetaObject::invokeMethod(t_quickObjectReadChart , "setBusyIndicator",
                                  Q_ARG(QVariant, QVariant::fromValue(false)));

    });
}

void ExcRecordDisplayer::sl_settingFinishTable()
{
    QDateTime t_time;
    QVector<int> t_vector;
    static QSqlQuery query(m_fdb);

    QFuture < void > future =  QtConcurrent::run([this](){
        QSqlQuery query(m_fdb);
        QVector<int> t_vector;
        qDebug() << __FUNCTION__  << QThread::currentThreadId() << QThread::currentThread();
        if(query.exec("SELECT date,time,channel,ug,ig,il,usyn,ugd,igd,uk,p,q,f,us FROM drecorder")){

            //1.1-table
            QObject *t_quickObjectReadTable  = ((QObject *)m_quickMainScreen->rootObject())->findChild<QObject *>("page_7AnalogReaderTable");
            QMetaObject::invokeMethod(t_quickObjectReadTable , "setBusyIndicator",
                                      Q_ARG(QVariant, QVariant::fromValue(true)));
            //1.3-setting ui
            QVariant t_vari;
            QObject *t_quickObjectSettingUI  = ((QObject *)m_quickWidgetSetting->rootObject());

            //2.1-read start time
            t_vari = t_quickObjectSettingUI->property("dateStart");
            QDateTime t_timeStart = t_vari.toDateTime();

            //2.2-read end time
            t_vari = t_quickObjectSettingUI->property("dateEnd");
            QDateTime t_timeEnd = t_vari.toDateTime();

            //2.3-calculate time longtitu
            uint t_timeLong = t_timeEnd.toTime_t()-t_timeStart.toTime_t();
//            uint t_recorderLastTime=0;

            //3-read
            while(query.next()){
                QDateTime t_dataTime = QDateTime(query.value(0).toDate(), query.value(1).toTime());
                if(t_dataTime>t_timeEnd)
                    break;
                else if(t_dataTime<t_timeStart)
                    continue;

                t_vector.clear();
                t_vector.push_back(query.value(3).toInt());
                t_vector.push_back(query.value(4).toInt());
                t_vector.push_back(query.value(5).toInt());
                t_vector.push_back(query.value(6).toInt());
                t_vector.push_back(query.value(7).toInt());
                t_vector.push_back(query.value(8).toInt());
                t_vector.push_back(query.value(9).toInt());
                t_vector.push_back(query.value(10).toInt());
                t_vector.push_back(query.value(11).toInt());
                t_vector.push_back(query.value(12).toInt());
                t_vector.push_back(query.value(13).toInt());

                //4.1-这个是B，则A缺失
                if(query.value(2).toString().contains('B')){
                    //5-to QML
                    QMetaObject::invokeMethod(t_quickObjectReadTable , "addModelFromCOnlyB",
                                              Q_ARG(QVariant, QVariant::fromValue(t_dataTime)),
                                              Q_ARG(QVariant, QVariant::fromValue(t_vector)));
                }
                //4.2-这个是A，下一个是？
                else if(query.value(2).toString().contains('A')){
                    query.next();
                    //4.3-下一个也是A，则B缺失
                    if(query.value(2).toString().contains('A'))
                    {
                        QMetaObject::invokeMethod(t_quickObjectReadTable , "addModelFromCOnlyA",
                                                  Q_ARG(QVariant, QVariant::fromValue(t_dataTime)),
                                                  Q_ARG(QVariant, QVariant::fromValue(t_vector)));
                        query.previous();
                    }
                    //4.4-AB都有
                    else if(query.value(2).toString().contains('B')){
                        t_vector.push_back(query.value(3).toInt());
                        t_vector.push_back(query.value(4).toInt());
                        t_vector.push_back(query.value(5).toInt());
                        t_vector.push_back(query.value(6).toInt());
                        t_vector.push_back(query.value(7).toInt());
                        t_vector.push_back(query.value(8).toInt());
                        t_vector.push_back(query.value(9).toInt());
                        t_vector.push_back(query.value(10).toInt());
                        t_vector.push_back(query.value(11).toInt());
                        t_vector.push_back(query.value(12).toInt());
                        t_vector.push_back(query.value(13).toInt());
                        QMetaObject::invokeMethod(t_quickObjectReadTable , "addModelFromC",
                                                  Q_ARG(QVariant, QVariant::fromValue(t_dataTime)),
                                                  Q_ARG(QVariant, QVariant::fromValue(t_vector)));
                    }
                }


                //6-keep program free and running
                uint t_recorderNowTime = t_dataTime.toTime_t();
                if(query.at()%100==0)
                {
                    long long t_nowTime = (long long)t_timeEnd.toTime_t()-t_recorderNowTime;
                    //                        qDebug() << t_nowTime << t_timeLong;
                    QMetaObject::invokeMethod(t_quickObjectReadTable , "setBusyIndicatorValue",
                                              Q_ARG(QVariant, QVariant::fromValue((1-(float)t_nowTime/t_timeLong)*100)));
                    QThread::msleep(300);
                }

            }
            QMetaObject::invokeMethod(t_quickObjectReadTable , "setBusyIndicator",
                                      Q_ARG(QVariant, QVariant::fromValue(false)));
        }

    });
}

//void ExcScreen::keyPressEvent(QKeyEvent *ev)
//{
//    if(ev->key() == Qt::Key_F11)
//    {sl_fullScreen();
//    }
//}
